package net.takela.common.web.model;

import com.alibaba.fastjson2.JSON;
import net.takela.common.utils.JSONUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;

import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;

public class Model implements Serializable {

	private static final Logger LOGGER = LoggerFactory.getLogger(Model.class);
    /**
     * 
     */
    public Object deepClone() {
        try {
            //将对象写到流里
            ByteArrayOutputStream bo = new ByteArrayOutputStream();
            ObjectOutputStream oo = new ObjectOutputStream(bo);
            oo.writeObject(this);
            //从流里读出来
            ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray());
            ObjectInputStream oi = new ObjectInputStream(bi);
            Object copy = oi.readObject();
            oi.close();
            bi.close();
            oo.close();
            bo.close();
            return copy;

        } catch (Exception e) {
			LOGGER.error("deepClone fail", e);
        }
        return null;
    }

    /**
     *
     */
    /**
     * 
     */
    @Override
    public String toString() {
        return JSONUtils.toString(this);
    }
    /**
     * 
     */
    public <T> T copyTo(Class<T> clazz) {
        return copyTo(clazz, (String[]) null);
    }
    /**
     * 
     */
    public <T> T copyTo(Class<T> clazz, String... ignoreFields) {
		T dest = null;
		try {
			dest = (T) clazz.getDeclaredConstructor().newInstance();
			BeanUtils.copyProperties(this, dest, ignoreFields);
		} catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
			LOGGER.error("copyTo fail", e);
		}
        return dest;
    }

    public Map<String, Object> toMap() {
        return JSON.parseObject(JSON.toJSONString(this));
    }
}
